package com.hzp.net.server;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;


@Slf4j
class AcceptHandler extends Handler implements Runnable {
    public AcceptHandler(SelectionKey key) {
        super(key);
    }

    @Override
    public void run() {
        //处理连接
        ServerSocketChannel channel = (ServerSocketChannel) getKey().channel();   //通过key找到对应的channel
        try {
            SocketChannel client = channel.accept();
            client.configureBlocking(false);
            client.register(getKey().selector(), SelectionKey.OP_READ);
            getKey().interestOps(SelectionKey.OP_ACCEPT);
            log.info(client.getRemoteAddress() + "上线了！");
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(new String("已连接成功").getBytes(Charset.forName("UTF-8")));
            client.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
